<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AliOosService;
use app\admin\service\CommunityService;
use app\admin\service\EnterprisePathService;
use app\admin\service\EnterpriseRejectService;
use app\admin\service\EnterpriseService;
use app\admin\service\LocationService;
use app\admin\service\RecruitService;
use app\admin\service\IndustryCateService;
use app\admin\service\SubscribeLogService;
use app\admin\service\UsersService;
use app\admin\validate\Enterprise as EnterpriseValidate;
use app\AdminController;
use think\exception\ValidateException;
use think\facade\Log;

/**
 * 企业管理
 * Class Enterprise
 * @package app\admin\controller
 */
class Enterprise extends AdminController
{
    /**
     * 企业列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $where = [];
        if (request()->isPost()) {
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = ['e.name|ce.name|c.name', 'like', '%' . $keywords . '%'];
            }

            $where[] = ['e.status', '=', 1];
            $list = EnterpriseService::getEnterpriseList($where, $this->page, $this->pagesize);
            $count = EnterpriseService::countEnterpriseList($where);

            return adminResponseJson(['list' => $list, 'count' => $count]);
        }

        return view();
    }

    /**
     * 企业添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function enterpriseAdd()
    {
        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(EnterpriseValidate::class)->enterpriseInsert()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (!$data['other_cate'] && !$data['cid']) {
                $this->error(adminJsonMsg(10029));
            }

            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10010));
            }

            $data['unique_key'] = md5($data['name'] . $data['uid']);
            $enterprise = EnterpriseService::findEnterprise([
                ['unique_key', '=', $data['unique_key']],
                ['status', '<>', 2],
            ]);
            if ($enterprise) {
                $this->error(adminJsonMsg(10028));
            }

            $cidArr = $this->createOtherCate($data['other_cate'], $data['cid']);
            // 一级id
            $data['pid'] = $cidArr['pid'];
            // 二级id
            $data['cid'] = $cidArr['cid'];

            if ($data['other_cate']) {
                Log::write('企业添加-自定义添加了所属行业' . $data['other_cate'], 'error');

                $industryCate = IndustryCateService::findIndustryCate(['name' => $data['other_cate'], 'status' => 1]);
                // 存在
                if ($industryCate) {
                    // 当前输入行业存在一级分类中
                    if ($industryCate['pid'] == 0) {
                        $this->error(adminJsonMsg(10030));
                    }
                    // 存在二级分类中，直接获取已存在的id
                    $data['cid'] = $industryCate['id'];

                    // 不存在，新增到 “其它”一级分类下
                } else {
                    $r = IndustryCateService::createIndustryCate([
                        'pid' => 148,
                        'name' => trim($data['other_cate'])
                    ]);
                    $data['cid'] = $r['id'];
                }
            }

            // 1 => 已通过
            $data['status'] = 1;

            $res = EnterpriseService::createEnterprise($data);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $pathsArr = $data['paths'] ? explode(',', $data['paths']) : [];
            if ($pathsArr) {
                foreach ($pathsArr as $path) {
                    EnterprisePathService::createEnterprisePath([
                        'eid' => $res->id,
                        'path' => $path,
                    ]);
                }
            }

            $pathsArr[] = $data['qrcode'];
            $pathsArr[] = $data['logo'];

            AliOosService::uploadAliOos($pathsArr);

            $this->success(adminJsonMsg(1004), (STRING)url('/enterprise/index'));
        }

        // 行业
        $list['industryCate'] = IndustryCateService::getIndustryCate();
        // 省份
        $list['province'] = LocationService::getProvince();

        return view('', ['list' => $list]);
    }

    /**
     * 企业编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function enterpriseEdit()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = EnterpriseService::findEnterprise(['id' => $id, 'status' => 1]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        $info['yqrcode'] = config('url.url') . $info['qrcode'];
        $info['ylogo'] = config('url.url') . $info['logo'];

        // 企业图片资源
        $path_list = EnterprisePathService::getEnterprisePath(['eid' => $info['id']], 0);
        $info['images_list'] = '';
        $info['images_path'] = '';
        $yPathsArr = [];
        if ($path_list) {
            $path = '';
            $images_path = '';
            foreach ($path_list as $v) {
                $path .= config('url.url') . $v['path'] . ',';
                $images_path .= $v['path'] . ',';
                $yPathsArr[] = $v['path'];
            }
            $info['images_list'] = rtrim($path, ',');
            $info['images_path'] = rtrim($images_path, ',');
        }

        if (request()->isPost()) {
            $data = request()->post();

            try {
                validate(EnterpriseValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (!$data['other_cate'] && !$data['cid']) {
                $this->error(adminJsonMsg(10029));
            }

            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10010));
            }

            $data['unique_key'] = md5($data['name'] . $data['uid']);
            $enterprise = EnterpriseService::findEnterprise([
                ['unique_key', '=', $data['unique_key']],
                ['status', '<>', 2],
                ['id', '<>', $data['id']],
            ]);
            if ($enterprise) {
                $this->error(adminJsonMsg(10028));
            }

            $cidArr = $this->createOtherCate($data['other_cate'], $data['cid']);
            // 一级id
            $data['pid'] = $cidArr['pid'];
            // 二级id
            $data['cid'] = $cidArr['cid'];

            // 1 => 已通过
            $data['status'] = 1;

            $res = EnterpriseService::updateEnterprise($data, ['id' => $data['id']]);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $pathsArr = $data['paths'] ? explode(',', $data['paths']) : [];

            // 比对是否新增了企业图片
            $addPathArr = array_diff($pathsArr, $yPathsArr);
            if ($addPathArr) {
                foreach ($addPathArr as $path) {
                    EnterprisePathService::createEnterprisePath([
                        'eid' => $data['id'],
                        'path' => $path,
                    ]);
                }
            }

            $savePaths = [];
            // 修改了二维码
            if ($data['qrcode'] != $info['qrcode']) {
                $savePaths[] = $data['qrcode'];
            }

            // 修改了logo
            if ($data['logo'] != $info['logo']) {
                $savePaths[] = $data['logo'];
            }

            $addPathArr = array_merge($addPathArr, $savePaths);

            AliOosService::uploadAliOos($addPathArr);

            // 比对是否删除了企业图片
            $delPathArr = array_diff($yPathsArr, $pathsArr);

            // 删除资源数据
            if ($delPathArr) {
                foreach ($delPathArr as $path) {
                    EnterprisePathService::delEnterprisePath(['eid' => $data['id'], 'path' => $path]);
                }
            }

            $this->success(adminJsonMsg(1004), (STRING)url('/enterprise/index'));
        }

        // 一级行业分类
        $list['topCate'] = IndustryCateService::getIndustryCate();
        // 当前二级行业分类所属pid
        $info['pid'] = IndustryCateService::findIndustryCateValue(['id' => $info['cid']], 'pid');
        // 二级行业分类
        $list['childCate'] = IndustryCateService::getIndustryCate($info['pid']);
        // 省份
        $list['province'] = LocationService::getProvince();
        // 城市
        $list['city'] = LocationService::getCity($info['province']);
        // 地区
        $list['area'] = LocationService::getArea($info['city']);

        return view('', ['info' => $info, 'list' => $list]);
    }

    /**
     * 企业详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function enterpriseShow()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = EnterpriseService::findEnterprise(['id' => $id], 1);

        return view('', ['info' => $info, 'source' => intval($this->request->param('source', 0))]);
    }

    /**
     * 修改状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus()
    {
        if (request()->isPost()) {

            $id = intval($this->request->param('id', 0));
            // 2=>删除  1=>通过  -1=>驳回
            $status = intval($this->request->param('status', 2));
            // 驳回原因
            $reason = $this->request->param('reject_reason', '');
            if (!$id) {
                $this->error(adminJsonMsg(1001));
            }

            $where = ['id' => $id];
            $info = EnterpriseService::findEnterprise($where);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            $update = ['status' => $status];
            EnterpriseService::updateEnterprise($update, $where);

            // 删除关联的
            if ($status == 2) {
                $where1 = ['eid' => $id];
                // 社群
                CommunityService::updateCommunity($update, $where1);
                // 招聘
                RecruitService::updateRecruit($update, $where1);
            }

            if ($status == -1) {
                // 写入驳回记录表
                EnterpriseRejectService::createEnterpriseReject([
                    'eid' => $id,
                    'reason' => $reason,
                    'reject_time' => time(),
                ]);
            }

            // 通过/驳回，推送消息
            if (in_array($status, [1, -1])) {
                $map = [
                    // 关联表id
                    'relation_id' => $id,
                    'uid' => $info['uid'],
                    // 1企业  2社群  3招聘
                    'type' => 1,
                    'is_push' => 0
                ];
                SubscribeLogService::updateSubscribeLog($map, [
                    'status' => $status
                ]);
            }

            $this->success(adminJsonMsg(1004));
        }
    }
}